import { Chat } from '@/types'
import { currentChatIdAtom } from '@/atoms'
import { useAtomValue } from 'jotai'
import { useState, useRef, useCallback } from 'react'
import clsx from 'clsx'
import { useTranslation } from 'react-i18next'
import {
  ListItem, ListItemText, ListItemButton, ListItemIcon, IconButton,
  Menu, MenuItem,
  TextField, Typography,
} from '@mui/material'
import useChat from '@/hooks/useChat'
import { showAlertDialog } from '../Base/Alert'

// 操作按钮组件
function OperateBtn({ session }: { session: Chat }) {
  const { t } = useTranslation()
  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLButtonElement>(null)
  const { copyChat, removeChat } = useChat()

  const copy = useCallback(() => {
    copyChat(session)
    setOpen(false)
  }, [session])

  const deleteSession = useCallback(() => {
    showAlertDialog({
      title: t('make sure for delete'),
      content: t('cant reply if delete'),
      onOk: () => {
        removeChat(session)
        setOpen(false)
      },
    })
  }, [session])

  return (
    <>
      <IconButton ref={ref} onClick={() => setOpen(true)}>
        <div className="i-material-symbols:more-horiz text-1rem" />
      </IconButton>
      <Menu
        open={open}
        anchorEl={ref.current}
        onClose={() => setOpen(false)}
      >
        <MenuItem onClick={deleteSession}>
          <ListItemIcon>
            <div className="i-material-symbols:delete-outline-rounded" />
          </ListItemIcon>
          <ListItemText>DELETE</ListItemText>
        </MenuItem>
        <MenuItem onClick={copy}>
          <ListItemIcon>
            <div className="i-material-symbols:content-copy-outline-rounded" />
          </ListItemIcon>
          <ListItemText>COPY</ListItemText>
        </MenuItem>
      </Menu>
    </>
  )
}

// 可编辑文本组件
const EditableText = ({ session }: { session: Chat }) => {
  const [text, setText] = useState(session.name)
  const [isEditing, setIsEditing] = useState(false)
  const { modifyChatInfo } = useChat()

  const handleSave = useCallback(() => {
    modifyChatInfo({ ...session, name: text })
    setIsEditing(false)
  }, [session.id, text])

  return isEditing
    ? (
        <TextField
          autoFocus
          value={text}
          onBlur={handleSave}
          size="small"
          sx={{ input: { padding: 0 } }}
          onChange={e => setText(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter') handleSave() }}
        />
      )
    : (
        <Typography
          onDoubleClick={() => setIsEditing(true)}
          className="overflow-hidden truncate"
          style={{ cursor: 'pointer' }}
        >
          {session.name}
        </Typography>
      )
}

// 会话条目组件
export default function SessionItem({ session }: { session: Chat }) {
  const currentSessionId = useAtomValue(currentChatIdAtom)
  const { switchChat } = useChat()

  return (
    <ListItem
      disablePadding
      key={session.id}
      className={clsx({ 'bg-gray-200 dark:bg-gray-800': currentSessionId === session.id })}
      onClick={() => switchChat(session.id)}
    >
      <ListItemButton sx={{ borderRadius: '0.5rem', padding: '0 auto' }}>
        <ListItemText>
          <EditableText session={session} />
        </ListItemText>
        <OperateBtn session={session} />
      </ListItemButton>
    </ListItem>
  )
}
